package system

import (
	"fmt"

	"go-api-template/service"
)

func Init() {
	var systemUserNum int64
	err := service.DB.AutoMigrate(
		&Role{},
		&RoleMenu{},
		&User{},
		&UserRole{},
		&CronExpr{},
		&BaseApi{},
		&Job{},
		&Menu{},
		&Article{},
		&ArticleTag{},
		&Tag{},
		&UserTrack{},
	)
	if err != nil {
		service.Log.Error(err.Error())
	}

	// 创建分表
	for i := 0; i < 4; i++ {
		tableName := fmt.Sprintf("system_user_track_%d", i)
		_ = service.DB.Table(tableName).AutoMigrate(&UserTrack{})
	}

	// 初始化用户
	if err = service.DB.Model(&User{}).Count(&systemUserNum).Error; err != nil {
		panic("db init panic")
	} else if systemUserNum == 0 {
		var su = User{
			Account:  "admin",
			Username: "admin",
			Email:    "admin@mail.com",
			Password: "123123",
			IsAdmin:  1,
		}
		service.DB.Create(&su)
	}
}

func GetTableNameById(baseTable string, id string) string {
	hash := 0
	for _, c := range id {
		hash = int(c) + ((hash << 5) - hash)
	}
	tableNumber := hash % 4
	if tableNumber < 0 {
		tableNumber = -tableNumber
	}
	return fmt.Sprintf("%s_%d", baseTable, tableNumber)
}
